const {PORT} =  require("../utils/constant")
const express = require('express');
const Router = express.Router()

const multer = require('multer');

let path = './public/img/avatar';

const AVATAR_BASE_URL = `http://localhost:${PORT}/static/img/avatar/`

const BGIMG_BASE_URL = `http://localhost:${PORT}/static/img/bgImg/`

// 文件上传中间件
const upload = multer({
    // 文件限制
    limits: {
        // 限制文件大小
        fileSize: 1024 * 500,
        files: 1,
    },
    // 文件过滤
    fileFilter(req, file, cb) {
        console.log('打印1',req.body);
        if (file.mimetype == 'image/png' || file.mimetype == 'image/jpeg' || file.mimetype == 'image/gif') {
            cb(null, true)
        } else {
            cb(null, false)
        }
    },
    // 文件存储磁盘设置
    storage: multer.diskStorage({
        destination: function (req, file, cb) {
            // if (req.body.tag == 'avatar') {
            //     path = './public/img/avatar'
            // } else if (req.body.tag == 'bgImg') {
            //     path = './public/img/bgImg'
            // }
            console.log('打印2',req.body);
            cb(null, path)
        },
        filename: function (req, file, cb) {
            const fileName = (new Date().getTime()) + '-' + file.originalname
            cb(null, fileName)
        }
    })
})

Router.post('/uploadImg', upload.single('haha'), (req, res) => {
    console.log('文件',req.file);
    
    let url = AVATAR_BASE_URL + req.file.filename;
    // if (path === './public/img/avatar') {
    //     url = AVATAR_BASE_URL + req.file.filename
    // } else if (path === './public/img/bgImg') {
    //     url = BGIMG_BASE_URL + req.file.filename
    // }
    res.send({
        success: true,
        code: 200,
        msg: "上传成功123",
        url,
    })
})

module.exports = Router
